//
//  AppDelegate.m
//  Mehfile Zainab
//
//  Created by Sitara Badourali on 10/11/12.
//  Copyright (c) 2012 Sitara Badourali. All rights reserved.
//

#import "AppDelegate.h"

#import "MZContactsViewController.h"
#import "MZGalleryViewController.h"
#import "MZProgramViewController.h"
#import "MZNewsViewController.h"
#import "MZTimeTableSegmentedViewController.h"
#import "SplashScreenViewController.h"
#import "Mehfile_ZainabViewController.h"
#import "MZViewController.h"
#import "SMRotaryWheel.h"
#import <AudioToolbox/AudioToolbox.h>
#import "CustomBadge.h"
#import "GAI.h"
#import "Appirater.h"

@implementation AppDelegate

- (void)dealloc
{
    [_window release];
    //[_tabBarController release];
    [_mzViewController release];
    [_mzNavigationController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    
    /*
    self.mzViewController = [[Mehfile_ZainabViewController alloc]
                                  initWithNibName:@"Mehfile_ZainabViewController"
                                  bundle:nil];
    */
    
    UIGraphicsBeginImageContext(self.window.frame.size);
    //[[UIImage imageNamed:@"fond.jpg"] drawInRect:self.window.bounds];
    [[UIImage imageNamed:@"fond-autre-page.jpg"] drawInRect:self.window.bounds];
    UIImage *backImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.window.backgroundColor = [UIColor colorWithPatternImage:backImage];
    
    /*
    UIView *backgroundView = [[UIView alloc] initWithFrame:self.window.frame];
    backgroundView.backgroundColor = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"fond.jpg"] scaleToSize:CGSizeMake(self.window.frame.size.width, self.window.frame.size.height)]];
    [self.window addSubview:backgroundView];
    [backgroundView release];
    */
    
    [[UINavigationBar appearance] setTitleTextAttributes: @{
                    UITextAttributeTextColor: [UIColor colorWithRed:48 green:86 blue:38 alpha:0.6],
                    //UITextAttributeTextShadowColor: [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8],
                    //UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)],
                    UITextAttributeFont: [UIFont fontWithName:@"Futura-CondensedMedium" size:20.0f]
     }];
    
    NSDictionary *remoteNotif = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    NSString *notifType = [remoteNotif valueForKey:@"type"];
    NSLog(@"Remote notification type is : %@",notifType);
    
    /*
    if (notifType != nil)
    {
        // Clear application badge when app launches
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
    */
    // Instead of removing application badge when notification type is defined (code above)
    // we remove the badge even if notification is nil
    // Users will be able to see the badge removed easily
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    self.mzViewController = [[MZViewController alloc]
                             initWithNibName:@"MZViewController"
                             bundle:nil];

    self.mzViewController.title = @"Mehfile Zainab";
    
    self.mzNavigationController = [[UINavigationController alloc] initWithRootViewController:self.mzViewController];
    
    // Prevent the navigation bar to not overlap the UI when building with SDK7
    self.mzNavigationController.navigationBar.translucent = NO;
    
    /*
    self.mzNavigationController.navigationBar.translucent = YES;
    self.mzViewController.wantsFullScreenLayout = YES;
    */
    
    /*
    UIImageView *bckGroundImage = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"Home-retina.png"] scaleToSize:CGSizeMake(self.mzViewController.view.frame.size.width, self.mzViewController.view.frame.size.height)]];
    [self.mzViewController.view addSubview:bckGroundImage];
    [self.mzViewController.view sendSubviewToBack:bckGroundImage];
    [bckGroundImage release];
    */
    
    UINavigationBar *navBar = [self.mzNavigationController navigationBar];
    //UIImage *backgroundImage = [UIImage imageNamed:@"Home_0000_navigation-bar.png"];
    UIImage *backgroundImage = [UIImage imageNamed:@"Navigation-bar.jpg"];
    //[backgroundImage drawInRect:traCGRectMake(0, 0, navBar.frame.size.width, navBar.frame.size.height)];
    [navBar setBackgroundImage:[backgroundImage scaleToSize:CGSizeMake(navBar.frame.size.width, navBar.frame.size.height)] forBarMetrics:UIBarMetricsDefault];
    
    /*
    UIImageView *separatorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home.png"]];
    separatorImage.contentMode = UIViewContentModeScaleAspectFit;
    [self.mzViewController.view addSubview:separatorImage];
    [separatorImage release];
    */
    
    NSInteger retina4coeff = 0;
    
    /*
    if ([UIScreen mainScreen].bounds.size.height==480) {
        NSLog(@"iPhone 4");
    }
    */
    
    if ([UIScreen mainScreen].bounds.size.height==568) {
        NSLog(@"iPhone 5");
        retina4coeff = 22;
    }
    
    NSInteger overlap_X = 15;
    NSInteger overlap_Y = 60;
    float reduction = 1.5;
    
    CGRect naRect = CGRectMake(15+overlap_X, 170-overlap_Y+retina4coeff, 59/reduction, 57/reduction);
    CGRect naLabelRect_1 = CGRectMake(10, 150+retina4coeff, 90, 25.0);
    CGRect naLabelRect_2 = CGRectMake(10, 170+retina4coeff, 90, 25.0);
    
    CGRect neRect = CGRectMake(115+overlap_X, 105-overlap_Y+retina4coeff, 84/reduction, 65/reduction);
    CGRect neLabelRect = CGRectMake(115, 95+retina4coeff, 90, 25.0);
    
    CGRect pRect = CGRectMake(235+overlap_X, 170-overlap_Y+retina4coeff, 61/reduction, 66/reduction);
    CGRect pLabelRect = CGRectMake(225, 160+retina4coeff, 90, 25.0);
    
    CGRect cRect = CGRectMake(230+overlap_X, 295-overlap_Y+retina4coeff*2, 67/reduction, 66/reduction);
    CGRect cLabelRect = CGRectMake(225, 285+retina4coeff*2, 90, 25.0);
    
    CGRect iRect = CGRectMake(140+overlap_X, 365-overlap_Y+retina4coeff*2, 27/reduction, 66/reduction);
    CGRect iLabelRect = CGRectMake(115, 355+retina4coeff*2, 90, 25.0);
    
    CGRect aRect = CGRectMake(15+overlap_X, 300-overlap_Y+retina4coeff*2, 60/reduction, 52/reduction);
    CGRect aLabelRect = CGRectMake(10, 285+retina4coeff*2, 90, 25.0);
    
    /*
    [self addButton:@"Home_0005s_0009_Informations" inFrame:CGRectMake(15, 180-overlap, 90, 65) forSelector:@selector(displayInfos)];
    [self addButton:@"Home_0005s_0008_Programme" inFrame:CGRectMake(115, 115-overlap, 90, 65) forSelector:@selector(displayProgram) forNotification:notifType];
    [self addButton:@"Home_0005s_0000_News" inFrame:CGRectMake(235, 180-overlap, 50, 65) forSelector:@selector(displayNews) forNotification:notifType];
    [self addButton:@"Home_0005s_0004_Albums" inFrame:CGRectMake(230, 295-overlap, 60, 65) forSelector:@selector(displayGallery)];
    [self addButton:@"Home_0005s_0002_Contact" inFrame:CGRectMake(130, 355-overlap, 60, 55) forSelector:@selector(displayContacts)];
    [self addButton:@"Home_0005s_0008_Horaires-Namaaz" inFrame:CGRectMake(30, 295-overlap, 60, 65) forSelector:@selector(displayTimeTable)];
    */
    
    [self addLabel:@"Horaires" inFrame:naLabelRect_1 forSize:15];
    [self addLabel:@"Namaaz" inFrame:naLabelRect_2 forSize:15];
    [self addLabel:@"News" inFrame:neLabelRect forSize:15];
    [self addLabel:@"Programme" inFrame:pLabelRect forSize:15];
    [self addLabel:@"Contact" inFrame:cLabelRect forSize:15];
    [self addLabel:@"Informations" inFrame:iLabelRect forSize:15];
    [self addLabel:@"Albums" inFrame:aLabelRect forSize:15];
    
    [self addButton:@"namaaz-icon" forState:@"namaaz-icon-pressed" inFrame:naRect forSelector:@selector(displayTimeTable)];
    [self addButton:@"contact-icon" forState:@"contact-icon-pressed" inFrame:cRect forSelector:@selector(displayContacts)];
    
    [self addButton:@"information-icon" forState:@"information-icon-pressed" inFrame:iRect forSelector:@selector(displayInfos)];
    
	// Temporary disabled
	// Feature to enable for future release
	/*
    [self addButton:@"information-icon" forState:@"information-icon-pressed" inFrame:iRect forSelector:@selector(displayYoutube)];
	*/
	
    [self addButton:@"albums-icon" forState:@"albums-icon-pressed" inFrame:aRect forSelector:@selector(displayGallery)];
	
    if ([notifType isEqualToString:@"News"]) {
        [self addButton:@"news-icon" forState:@"news-icon-pressed" inFrame:neRect forSelector:@selector(displayNews) forNotification:notifType];
    } else {
        [self addButton:@"news-icon" forState:@"news-icon-pressed" inFrame:neRect forSelector:@selector(displayNews)];
    }
    if ([notifType isEqualToString:@"Programme"]) {
        [self addButton:@"programme-icon" forState:@"programme-icon-pressed" inFrame:pRect forSelector:@selector(displayProgram) forNotification:notifType];
    } else {
        [self addButton:@"programme-icon" forState:@"programme-icon-pressed" inFrame:pRect forSelector:@selector(displayProgram)];
    }
    
    /*
    CustomBadge *customBadge;
    customBadge = [CustomBadge customBadgeWithString:@"1"
                                     withStringColor:[UIColor whiteColor]
                                      withInsetColor:[UIColor redColor]
                                      withBadgeFrame:YES
                                 withBadgeFrameColor:[UIColor whiteColor]
                                           withScale:1.0
                                         withShining:YES];
    [customBadge setFrame:CGRectMake((neRect.origin.x+neRect.size.width)-(customBadge.frame.size.width/2), neRect.origin.y-(customBadge.frame.size.height/2), customBadge.frame.size.width, customBadge.frame.size.height)];
    [self.mzViewController.view addSubview:customBadge];
    customBadge = [CustomBadge customBadgeWithString:@"1"
                                     withStringColor:[UIColor whiteColor]
                                      withInsetColor:[UIColor redColor]
                                      withBadgeFrame:YES
                                 withBadgeFrameColor:[UIColor whiteColor]
                                           withScale:1.0
                                         withShining:YES];
    [customBadge setFrame:CGRectMake((pRect.origin.x+pRect.size.width)-(customBadge.frame.size.width/2), pRect.origin.y-(customBadge.frame.size.height/2), customBadge.frame.size.width, customBadge.frame.size.height)];
    [self.mzViewController.view addSubview:customBadge];
     */
    
    /*
    [self addButton:@"news-icon" forState:@"news-icon-pressed" inFrame:neRect forSelector:@selector(displayNews) forNotification:@"News"];
    [self addButton:@"programme-icon" forState:@"programme-icon-pressed" inFrame:pRect forSelector:@selector(displayProgram) forNotification:@"Programme"];
    */
    
    [[self window] setRootViewController:self.mzNavigationController];
    
    [self.window makeKeyAndVisible];
    
    NSLog(@"Present Splash Screen as a modal view");
    
	SplashScreenViewController *splashScreenViewController = [[SplashScreenViewController alloc]
                                                                initWithNibName:@"SplashScreenViewController" bundle:nil];
	splashScreenViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    //[self.tabBarController presentModalViewController:splashScreenViewController animated:NO];
    //[self.mzNavigationController presentModalViewController:splashScreenViewController animated:NO];
    [self.mzNavigationController presentViewController:splashScreenViewController animated:NO completion:nil];
    
    NSLog(@"******************** Registering for Push notifications ********************");
    
    // Add registration for remote notifications
    [[UIApplication sharedApplication]
     registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
	
	/*
	 
	NSLog(@"******************** Initializing Google Analytics ********************");
	
	// Optional: automatically send uncaught exceptions to Google Analytics.
	[GAI sharedInstance].trackUncaughtExceptions = YES;
	
	// Optional: set Google Analytics dispatch interval to e.g. 20 seconds.
	[GAI sharedInstance].dispatchInterval = 20;
	
	// Optional: set Logger to VERBOSE for debug information.
	//[[[GAI sharedInstance] logger] setLogLevel:kGAILogLevelVerbose];
	[[[GAI sharedInstance] logger] setLogLevel:kGAILogLevelError];
	
	// Initialize tracker.
	//id<GAITracker> tracker = [[GAI sharedInstance] trackerWithTrackingId:@"UA-47300647-1"];
	[[GAI sharedInstance] trackerWithTrackingId:@"UA-47300647-1"];
	
	*/
	
	NSLog(@"******************** AppIRater ********************");
	
	[Appirater setAppId:@"605553550"];
	[Appirater setDaysUntilPrompt:7];
	[Appirater setUsesUntilPrompt:5];
	[Appirater setSignificantEventsUntilPrompt:-1];
	[Appirater setTimeBeforeReminding:7];
	[Appirater setDebug:NO];
	[Appirater appLaunched:YES];
	
    return YES;

}

- (UIColor *)colorFromHexString:(NSString *)hexString {
    unsigned rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    [scanner setScanLocation:1]; // bypass '#' character
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}

/*
 * ------------------------------------------------------------------------------------------
 *  BEGIN APNS CODE
 * ------------------------------------------------------------------------------------------
 */

/**
 * Fetch and Format Device Token and Register Important Information to Remote Server
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
    
#if !TARGET_IPHONE_SIMULATOR
    
    NSLog(@"My token is: %@", devToken);
    
	// Get Bundle Info for Remote Registration (handy if you have more than one app)
	NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
	NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    
    /*
	// Check what Notifications the user has turned on.  We registered for all three, but they may have manually disabled some or all of them.
	NSUInteger rntypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
    
	// Set the defaults to disabled unless we find otherwise...
	NSString *pushBadge = @"disabled";
	NSString *pushAlert = @"disabled";
	NSString *pushSound = @"disabled";
    
	// Check what Registered Types are turned on. This is a bit tricky since if two are enabled, and one is off, it will return a number 2... not telling you which
	// one is actually disabled. So we are literally checking to see if rnTypes matches what is turned on, instead of by number. The "tricky" part is that the
	// single notification types will only match if they are the ONLY one enabled.  Likewise, when we are checking for a pair of notifications, it will only be
	// true if those two notifications are on.  This is why the code is written this way
	if(rntypes == UIRemoteNotificationTypeBadge){
		pushBadge = @"enabled";
	}
	else if(rntypes == UIRemoteNotificationTypeAlert){
		pushAlert = @"enabled";
	}
	else if(rntypes == UIRemoteNotificationTypeSound){
		pushSound = @"enabled";
	}
	else if(rntypes == ( UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert)){
		pushBadge = @"enabled";
		pushAlert = @"enabled";
	}
	else if(rntypes == ( UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)){
		pushBadge = @"enabled";
		pushSound = @"enabled";
	}
	else if(rntypes == ( UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)){
		pushAlert = @"enabled";
		pushSound = @"enabled";
	}
	else if(rntypes == ( UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)){
		pushBadge = @"enabled";
		pushAlert = @"enabled";
		pushSound = @"enabled";
	}
    */
    
	// Get the users Device Model, Display Name, Unique ID, Token & Version Number
	UIDevice *dev = [UIDevice currentDevice];
	NSString *deviceUuid = [dev.identifierForVendor UUIDString];
    NSString *deviceName = dev.name;
	NSString *deviceModel = dev.model;
	NSString *deviceSystemVersion = dev.systemVersion;
    
	// Prepare the Device Token for Registration (remove spaces and < >)
	NSString *deviceToken = [[[[devToken description]
                               stringByReplacingOccurrencesOfString:@"<"withString:@""]
                              stringByReplacingOccurrencesOfString:@">" withString:@""]
                             stringByReplacingOccurrencesOfString: @" " withString: @""];
    
	// Build URL String for Registration
	// !!! CHANGE "www.mywebsite.com" TO YOUR WEBSITE. Leave out the http://
	// !!! SAMPLE: "secure.awesomeapp.com"
	//NSString *host = @"192.168.1.99:8888";
    //NSString *host = @"sitara.azad.free.fr";
    NSString *host = @"zainabia-media.com";
    
	// !!! CHANGE "/apns.php?" TO THE PATH TO WHERE apns.php IS INSTALLED
	// !!! ( MUST START WITH / AND END WITH ? ).
	// !!! SAMPLE: "/path/to/apns.php?"
	//NSString *urlString = [@"/imzpush/apns.php?"stringByAppendingString:@"task=register"];
    //NSString *urlString = [@"/iosmehfile/imzpush/apns.php?"stringByAppendingString:@"task=register"];
    //NSString *urlString = @"/DevPush/register.php?";
    //NSString *urlString = @"/AdHocPush/register.php?";
    NSString *urlString = @"/iosmehfile/register.php?";
    
	urlString = [urlString stringByAppendingString:@"appname="];
	urlString = [urlString stringByAppendingString:appName];
	urlString = [urlString stringByAppendingString:@"&appversion="];
	urlString = [urlString stringByAppendingString:appVersion];
	urlString = [urlString stringByAppendingString:@"&deviceuid="];
	urlString = [urlString stringByAppendingString:deviceUuid];
	urlString = [urlString stringByAppendingString:@"&devicetoken="];
	urlString = [urlString stringByAppendingString:deviceToken];
	urlString = [urlString stringByAppendingString:@"&devicename="];
	urlString = [urlString stringByAppendingString:deviceName];
	urlString = [urlString stringByAppendingString:@"&devicemodel="];
	urlString = [urlString stringByAppendingString:deviceModel];
	urlString = [urlString stringByAppendingString:@"&deviceversion="];
	urlString = [urlString stringByAppendingString:deviceSystemVersion];
	/*
    urlString = [urlString stringByAppendingString:@"&pushbadge="];
	urlString = [urlString stringByAppendingString:pushBadge];
	urlString = [urlString stringByAppendingString:@"&pushalert="];
	urlString = [urlString stringByAppendingString:pushAlert];
	urlString = [urlString stringByAppendingString:@"&pushsound="];
	urlString = [urlString stringByAppendingString:pushSound];
    */
    
	// Register the Device Data
	// !!! CHANGE "http" TO "https" IF YOU ARE USING HTTPS PROTOCOL
	NSURL *url = [[NSURL alloc] initWithScheme:@"http" host:host path:urlString];
    
    //NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setTimeoutInterval:10];
    
	NSLog(@"Register URL: %@", url);
    
    //NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[[NSOperationQueue alloc] init] autorelease] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if (data)
        {
            NSLog(@"Return Data: %@", data);
        }
        if (error)
        {
            NSLog(@">>>>>>>>>>>>>>> Error when registering for Push : %@",[error localizedDescription]);
        }
    }];
    
	//NSLog(@"Return Data: %@", returnData);
    
#endif
}

/**
 * Failed to Register for Remote Notifications
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
#if !TARGET_IPHONE_SIMULATOR
    
	NSLog(@"Error in registration. Error: %@", error);
    
#endif
}

/**
 * Remote Notification Received while application was open.
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
#if !TARGET_IPHONE_SIMULATOR
    
	NSLog(@"Remote notification: %@",[userInfo description]);
	NSDictionary *apsInfo = [userInfo objectForKey:@"aps"];
    
	NSString *alert = [apsInfo objectForKey:@"alert"];
	NSLog(@"Received Push Alert: %@", alert);
    
	NSString *sound = [apsInfo objectForKey:@"sound"];
	NSLog(@"Received Push Sound: %@", sound);
	AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
	NSString *badge = [apsInfo objectForKey:@"badge"];
	NSLog(@"Received Push Badge: %@", badge);
	application.applicationIconBadgeNumber = [[apsInfo objectForKey:@"badge"] integerValue] -1;
    
    NSString *notifType = [userInfo objectForKey:@"type"];
	NSLog(@"Received Push type: %@", notifType);
    
    NSInteger retina4coeff = 0;
    
    /*
     if ([UIScreen mainScreen].bounds.size.height==480) {
     NSLog(@"iPhone 4");
     }
     */
    
    if ([UIScreen mainScreen].bounds.size.height==568) {
        NSLog(@"iPhone 5");
        retina4coeff = 22;
    }
    
    NSInteger overlap_X = 15;
    NSInteger overlap_Y = 60;
    float reduction = 1.5;
    
    CGRect neRect = CGRectMake(115+overlap_X, 105-overlap_Y+retina4coeff, 84/reduction, 65/reduction);
    //CGRect neLabelRect = CGRectMake(115, 95+retina4coeff, 90, 25.0);
    
    CGRect pRect = CGRectMake(235+overlap_X, 170-overlap_Y+retina4coeff, 61/reduction, 66/reduction);
    //CGRect pLabelRect = CGRectMake(225, 160+retina4coeff, 90, 25.0);
    
    CustomBadge *customBadge;
    if ([notifType isEqualToString:@"News"]) {
        customBadge = [CustomBadge customBadgeWithString:@"1"
                                         withStringColor:[UIColor whiteColor]
                                          withInsetColor:[UIColor redColor]
                                          withBadgeFrame:YES
                                     withBadgeFrameColor:[UIColor whiteColor]
                                               withScale:1.0
                                             withShining:YES];
        [customBadge setFrame:CGRectMake((neRect.origin.x+neRect.size.width)-(customBadge.frame.size.width/2), neRect.origin.y-(customBadge.frame.size.height/2), customBadge.frame.size.width, customBadge.frame.size.height)];
        [customBadge setTag:1];
        NSLog(@"Add custom badge of type %@",notifType);
        [self.mzViewController.view addSubview:customBadge];
    }
    if ([notifType isEqualToString:@"Programme"]) {
        customBadge = [CustomBadge customBadgeWithString:@"1"
                                         withStringColor:[UIColor whiteColor]
                                          withInsetColor:[UIColor redColor]
                                          withBadgeFrame:YES
                                     withBadgeFrameColor:[UIColor whiteColor]
                                               withScale:1.0
                                             withShining:YES];
        [customBadge setFrame:CGRectMake((pRect.origin.x+pRect.size.width)-(customBadge.frame.size.width/2), pRect.origin.y-(customBadge.frame.size.height/2), customBadge.frame.size.width, customBadge.frame.size.height)];
        [customBadge setTag:2];
        NSLog(@"Add custom badge of type %@",notifType);
        [self.mzViewController.view addSubview:customBadge];
    }
    
#endif
}

/*
 * ------------------------------------------------------------------------------------------
 *  END APNS CODE
 * ------------------------------------------------------------------------------------------
 */

-(void) addLabel:(NSString*)labelName inFrame:(CGRect)frameRect forSize:(NSInteger)fontSize {
    UILabel *textLabel = [ [UILabel alloc ] initWithFrame:frameRect];
    textLabel.textAlignment =  NSTextAlignmentCenter;
    textLabel.textColor = [self colorFromHexString:@"#b9ec69"];
    textLabel.backgroundColor = [UIColor clearColor];
    textLabel.font = [UIFont fontWithName:@"Futura-CondensedExtraBold" size:fontSize];
    [self.mzViewController.view addSubview:textLabel];
    textLabel.text = labelName;
}

-(void) addButton:(NSString*)imageName forState:(NSString*)highlightedImage inFrame:(CGRect)frameRect forSelector:(SEL)selector
{
    UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
    button.frame = frameRect;
    button.backgroundColor = [UIColor clearColor];
    [button addTarget:self.mzViewController action:selector forControlEvents:UIControlEventTouchUpInside];
    //[button setBackgroundImage:[[UIImage imageNamed:imageName] scaleToSize:CGSizeMake(button.frame.size.width, button.frame.size.width) ] forState:UIControlStateNormal];
    //[button setBackgroundImage:[[UIImage imageNamed:highlightedImage] scaleToSize:CGSizeMake(button.frame.size.width, button.frame.size.width) ] forState:UIControlStateHighlighted];
    [button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:highlightedImage] forState:UIControlStateHighlighted];
    button.contentMode = UIViewContentModeScaleToFill;
    NSLog(@"Badge position for %@ : %f, %f",imageName, (frameRect.origin.x+frameRect.size.width),(frameRect.origin.y));
    [self.mzViewController.view addSubview:button];
}

-(void) addButton:(NSString*)imageName forState:(NSString*)highlightedImage inFrame:(CGRect)frameRect forSelector:(SEL)selector forNotification:(NSString*)notificationType
{
    UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
    button.frame = frameRect;
    button.backgroundColor = [UIColor clearColor];
    [button addTarget:self.mzViewController action:selector forControlEvents:UIControlEventTouchUpInside];
    //[button setBackgroundImage:[[UIImage imageNamed:imageName] scaleToSize:CGSizeMake(button.frame.size.width, button.frame.size.width) ] forState:UIControlStateNormal];
    //[button setBackgroundImage:[[UIImage imageNamed:highlightedImage] scaleToSize:CGSizeMake(button.frame.size.width, button.frame.size.width) ] forState:UIControlStateHighlighted];
    [button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:highlightedImage] forState:UIControlStateHighlighted];
    button.contentMode = UIViewContentModeScaleToFill;
    NSLog(@"Badge position for %@ : %f, %f",imageName, (frameRect.origin.x+frameRect.size.width),(frameRect.origin.y));
    [self.mzViewController.view addSubview:button];
    CustomBadge *customBadge;
    if ([notificationType isEqualToString:@"News"]) {
        customBadge = [CustomBadge customBadgeWithString:@"1"
                                                          withStringColor:[UIColor whiteColor]
                                                           withInsetColor:[UIColor redColor]
                                                           withBadgeFrame:YES
                                                      withBadgeFrameColor:[UIColor whiteColor]
                                                                withScale:1.0
                                                              withShining:YES];
        [customBadge setFrame:CGRectMake((frameRect.origin.x+frameRect.size.width)-(customBadge.frame.size.width/2), (frameRect.origin.y)-(customBadge.frame.size.height/2), customBadge.frame.size.width, customBadge.frame.size.height)];
        [customBadge setTag:1];
        NSLog(@"Add custom badge of type %@",notificationType);
        [self.mzViewController.view addSubview:customBadge];
    }
    if ([notificationType isEqualToString:@"Programme"]) {
        customBadge = [CustomBadge customBadgeWithString:@"1"
                                                             withStringColor:[UIColor whiteColor]
                                                              withInsetColor:[UIColor redColor]
                                                              withBadgeFrame:YES
                                                         withBadgeFrameColor:[UIColor whiteColor]
                                                                   withScale:1.0
                                                                 withShining:YES];
        [customBadge setFrame:CGRectMake((frameRect.origin.x+frameRect.size.width)-(customBadge.frame.size.width/2), (frameRect.origin.y)-(customBadge.frame.size.height/2), customBadge.frame.size.width, customBadge.frame.size.height)];
        [customBadge setTag:2];
        NSLog(@"Add custom badge of type %@",notificationType);
        [self.mzViewController.view addSubview:customBadge];
    }
}

/*
-(void) buttonClicked
{
    NSLog(@"Button clicked!");
}
*/

/*
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
	NSLog(@"My token is: %@", deviceToken);
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
	NSLog(@"Failed to get token, error: %@", error);
}
*/

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    NSLog(@"A view controller has been selected for tab bar item");
}


/*
// Optional UITabBarControllerDelegate method.
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed
{
}
*/

/*
 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
     NSLog(@"Loading the different tab bars for navigation");
     
     //NSString *imageFile = @"info.png";
     UIBarButtonItem *addButton;
     UIImage *image;
     UIButton *button;
     UIView *v;
     
     MZProgramViewController *mzProgramViewController = [[MZProgramViewController alloc] initWithNibName:@"MZProgramViewController" bundle:nil];
     UINavigationController *mzProgramNavController = [[UINavigationController alloc] initWithRootViewController:mzProgramViewController];
     mzProgramViewController.title = MZ_PROGRAMS_VC_TITLE;
     
     image = [UIImage imageNamed:@"info.png"];
     button = [UIButton buttonWithType:UIButtonTypeCustom];
     [button setBackgroundImage: [image stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateNormal];
     [button setBackgroundImage: [[UIImage imageNamed: @"info.png"] stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateHighlighted];
     button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height);
     [button addTarget:mzProgramViewController action:@selector(showInfo:)    forControlEvents:UIControlEventTouchUpInside];
     v=[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ];
     [v addSubview:button];
     addButton = [[UIBarButtonItem alloc] initWithCustomView:v];
     
     //addButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:imageFile] style:UIBarButtonItemStylePlain target:mzProgramViewController action:@selector(showInfo:)];
     mzProgramViewController.navigationItem.rightBarButtonItem = addButton;
     [addButton release];
     
     MZNewsViewController *mzNewsViewController = [[MZNewsViewController alloc] initWithNibName:@"MZNewsViewController" bundle:nil];
     UINavigationController *mzNewsNavController = [[UINavigationController alloc] initWithRootViewController:mzNewsViewController];
     mzNewsViewController.title = MZ_NEWS_VC_TITLE;
     
     image = [UIImage imageNamed:@"info.png"];
     button = [UIButton buttonWithType:UIButtonTypeCustom];
     [button setBackgroundImage: [image stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateNormal];
     [button setBackgroundImage: [[UIImage imageNamed: @"info.png"] stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateHighlighted];
     button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height);
     [button addTarget:mzNewsViewController action:@selector(showInfo:)    forControlEvents:UIControlEventTouchUpInside];
     v=[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ];
     [v addSubview:button];
     addButton = [[UIBarButtonItem alloc] initWithCustomView:v];
     
     //addButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:imageFile] style:UIBarButtonItemStylePlain target:mzNewsViewController action:@selector(showInfo:)];
     mzNewsViewController.navigationItem.rightBarButtonItem = addButton;
     [addButton release];
     
     MZGalleryViewController *mzGalleryViewController = [[MZGalleryViewController alloc] initWithNibName:@"MZGalleryViewController" bundle:nil];
     UINavigationController *mzGalleryNavController = [[UINavigationController alloc] initWithRootViewController:mzGalleryViewController];
     mzGalleryViewController.title = MZ_GALLERY_VC_TITLE;
     
     image = [UIImage imageNamed:@"info.png"];
     button = [UIButton buttonWithType:UIButtonTypeCustom];
     [button setBackgroundImage: [image stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateNormal];
     [button setBackgroundImage: [[UIImage imageNamed: @"info.png"] stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateHighlighted];
     button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height);
     [button addTarget:mzGalleryViewController action:@selector(showInfo:)    forControlEvents:UIControlEventTouchUpInside];
     v=[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ];
     [v addSubview:button];
     addButton = [[UIBarButtonItem alloc] initWithCustomView:v];
     
     //addButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:imageFile] style:UIBarButtonItemStylePlain target:mzGalleryViewController action:@selector(showInfo:)];
     mzGalleryViewController.navigationItem.rightBarButtonItem = addButton;
     [addButton release];
     
     MZTimeTableSegmentedViewController *mzTimeTableViewController = [[MZTimeTableSegmentedViewController alloc] initWithNibName:@"MZTimeTableSegmentedViewController" bundle:nil];
     UINavigationController *mzTTNavController = [[UINavigationController alloc] initWithRootViewController:mzTimeTableViewController];
     mzTimeTableViewController.title = MZ_TIMETABLE_VC_TITLE;
     
     image = [UIImage imageNamed:@"info.png"];
     button = [UIButton buttonWithType:UIButtonTypeCustom];
     [button setBackgroundImage: [image stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateNormal];
     [button setBackgroundImage: [[UIImage imageNamed: @"info.png"] stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateHighlighted];
     button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height);
     [button addTarget:mzTimeTableViewController action:@selector(showInfo:)    forControlEvents:UIControlEventTouchUpInside];
     v=[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ];
     [v addSubview:button];
     addButton = [[UIBarButtonItem alloc] initWithCustomView:v];
     
     //addButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:imageFile] style:UIBarButtonItemStylePlain target:mzTimeTableViewController action:@selector(showInfo:)];
     mzTimeTableViewController.navigationItem.rightBarButtonItem = addButton;
     [addButton release];
     
     MZContactsViewController *mzContactsViewController = [[MZContactsViewController alloc] initWithNibName:@"MZContactsViewController" bundle:nil];
     UINavigationController *mzContactsNavController = [[UINavigationController alloc] initWithRootViewController:mzContactsViewController];
     mzContactsViewController.title = MZ_CONTACTS_VC_TITLE;
     
     image = [UIImage imageNamed:@"info.png"];
     button = [UIButton buttonWithType:UIButtonTypeCustom];
     [button setBackgroundImage: [image stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateNormal];
     [button setBackgroundImage: [[UIImage imageNamed: @"info.png"] stretchableImageWithLeftCapWidth:7.0 topCapHeight:0.0] forState:UIControlStateHighlighted];
     button.frame= CGRectMake(0.0, 0.0, image.size.width, image.size.height);
     [button addTarget:mzContactsViewController action:@selector(showInfo:)    forControlEvents:UIControlEventTouchUpInside];
     v=[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height) ];
     [v addSubview:button];
     addButton = [[UIBarButtonItem alloc] initWithCustomView:v];
     
     //addButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:imageFile] style:UIBarButtonItemStylePlain target:mzContactsViewController action:@selector(showInfo:)];
     mzContactsViewController.navigationItem.rightBarButtonItem = addButton;
     [addButton release];
     
     self.tabBarController = [[[UITabBarController alloc] init] autorelease];
     self.tabBarController.delegate = self;
     self.tabBarController.viewControllers = @[mzProgramNavController, mzNewsNavController, mzGalleryNavController, mzTTNavController, mzContactsNavController];
     
     self.window.rootViewController = self.tabBarController;
}
 
*/

@end
